<template>
  <div class="app-container">
      <avue-crud ref="crud"
                 :page="page"
                 :data="tableData"
                 :permission="permissionList"
                 :table-loading="tableLoading"
                 :option="tableOption"
                 :before-open="beforeOpen"
                 :upload-before="uploadBefore"
                 :upload-after="uploadAfter"
                 v-model="form"
                 @on-load="getPage"
                 @refresh-change="refreshChange"
                 @row-update="handleUpdate"
                 @row-save="handleSave"
                 @row-del="handleDel"
                 @sort-change="sortChange"
                 @search-change="searchChange"
                 @selection-change="selectionChange">
         <!-- <template slot="cityForm" slot-scope="scope">
              <el-select v-model="scope.row.city" clearable filterable placeholder="请选择">
                <el-option
                  v-for="dict in cityOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue">
                  <span style="float: left">{{ dict.dictLabel }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ dict.dictValue }}</span>
              </el-option>
              </el-select>
        </template> -->
         <template slot="mapForm" slot-scope="scope">
          <avue-map v-model="scope.row.map"></avue-map>
        </template>

        <template slot="logo" slot-scope="scope">
          <el-image v-if="scope.row.logo==null || scope.row.logo==''"
            style="width: 100px; height: 100px"
            :src="nopic">
          </el-image>
           <el-image v-else
            style="width: 100px; height: 100px"
            :src="scope.row.logo">
          </el-image>
        </template>
        <template slot="contentForm" slot-scope="scope">
          <BaseEditor v-model="scope.row.content"/>
        </template>

        <template slot="classDescForm" slot-scope="scope">
          <BaseEditor v-model="scope.row.classDesc"/>
        </template>
        <template slot="city" slot-scope="scope">
          {{citydata(scope.row.city)}}
        </template>
        <template slot="menu" slot-scope="scope">
          <el-button icon="el-icon-check"  :size="scope.size" :type="scope.type" @click="openmenu(scope)">绑定教练员</el-button>
        </template>

      </avue-crud>
      <el-dialog
      title="绑定教练"
      :visible.sync="dialogVisible"
      width="50%">
      <el-transfer
         filterable
         @change="handleChange"
         v-model="transferValue"
         :data="transferData"
         :props="{
            key: 'id',
            label: 'name'
          }"
         :filter-method="filterMethod"
         :titles="['教练列表', '绑定到俱乐部教练']"
         :button-texts="['删除绑定', '添加绑定']"
         filter-placeholder="请输入教练姓名">
      </el-transfer>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="dialogVisible = false">保 存</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
    import {checkPermi, getRole,isAdmin} from "@/utils/permission"
    import {getPage, getObj, addObj, putObj, delObj,getAllCoach,coachByClubid,bindCoach,cancelCoach} from '@/api/tennis/club'
    import {tableOption} from '@/const/crud/tennis/club'
    import { cityselect as getDictCityselect } from "@/api/system/dict/type";
    import {mapGetters} from 'vuex'
    import { getToken } from '@/utils/auth'
    import BaseEditor from '@/components/Editor/index.vue'

    export default {
        name: 'club',
        components: {
            BaseEditor,
        },
        data() {
            return {
                dialogVisible: false,
                nopic:'',
                checkPermi: checkPermi,
                form: {},
                dialogClubid:0,
                transferValue:[],
                transferData:[],
                tableData: [],
                cityOptions: [],
                cityDict:{},
                page: {
                    total: 0, // 总页数
                    currentPage: 1, // 当前页数
                    pageSize: 20, // 每页显示多少条
                    ascs: [],//升序字段
                    descs: 'add_time'//降序字段
                },
                paramsSearch: {},
                tableLoading: false,
                tableOption: tableOption,
                dialogAppraises: false,
                optionAppraises: {
                    props: {
                        avatar: 'nickName',
                        author: 'headimgUrl',
                        body: 'content'
                    }
                },
              selectionData: '',
              pointsConfig: null
            }
        },
        watch:{


        },
        created() {
          getDictCityselect().then(response => {
            this.cityOptions = response.data;
            let dict = {}
            for (let i in  response.data){
                  dict[response.data[i].dictValue]=response.data[i].dictLabel
            }
              this.cityDict = dict

           });
           if(isAdmin()!=true){
            // this.tableOption={}
            this.tableOption.group[0].column[1].disabled=true
            // console.log(this.tableOption)
          }
        },
        mounted: function () {
        },
        computed: {
            permissionList() {
                return {
                    addBtn: checkPermi(['tennis:club:add']),
                    delBtn: checkPermi(['tennis:club:remove']),
                    editBtn: checkPermi(['tennis:club:edit']),
                    viewBtn: checkPermi(['tennis:club:query'])
                };
            },
        },
        methods: {
          uploadAfter(res, done, loading,column) {
            // console.log(res,column)
            done()
            this.$message.success('上传后的方法')
          },
            handleChange(value, direction, movedKeys) {
              // console.log(value, direction, movedKeys);//direction movedKeys[0]
              if(direction==='right'){
                movedKeys.forEach((item)=>{
                  bindCoach(item,this.dialogClubid).then()
                })
              }else if(direction==='left'){
                 movedKeys.forEach((item)=>{
                  cancelCoach(item,this.dialogClubid).then()
                })
              }
            },
            filterMethod(query, item) {
              // console.log(item)
                return item.name.indexOf(query) > -1;
            },
            openmenu(scope){
              getAllCoach({}).then(response => {
                this.transferData = response.data
              })
              coachByClubid(scope.row.id).then(response =>{
                // console.log(response.data)
                let arr = []
                response.data.forEach((item)=>{
                  arr.push(item['id'])
                })
                this.transferValue = arr
              })
              this.dialogClubid = scope.row.id
              this.dialogVisible = true
            },
            citydata(id){
                  return this.cityDict[id+'']
            },
            selectionChange(list){
              this.selectionData = list
            },
            batchShelf(shelf){
              if(this.selectionData.length<=0){
                this.$message.error('请选择商品')
                return
              }
              let selectionIds = ''
              this.selectionData.forEach(item => {
                selectionIds += item.id+ ','
              })
              this.putObjShelf(selectionIds, shelf)
            },
            changeShelf(row){
              this.putObjShelf(row.id, row.shelf)
            },
            putObjShelf(ids, shelf){
                putObjShelf({
                  ids: ids,
                  shelf: shelf
                }).then(data => {
                  this.getPage(this.page)
                })
            },
            beforeOpen(done,type){
                if(type == 'add'){
                    this.$set(this.form,'map', {})
                    done()
                }else if(type == 'edit'){
                    this.tableLoading = true
                    getObj(this.form.id).then(response => {
                      this.$set(this.form,'map', {formattedAddress:this.form.address,
                         location:{lng:this.form.lontitude,lat:this.form.latitude}})
                        // console.log(response.data)
                      this.$set(this.form,'content', response.data.content)
                      this.$set(this.form,'classDesc', response.data.classDesc)
                       if(response.data.files.length!=0){
                          response.data.files.forEach((item,index,arr)=>{
                            arr[index]['value']=arr[index]['path']
                            arr[index]['label']=arr[index]['fName']
                          })
                        }
                      this.$set(this.form,'files',response.data.files)
                      this.tableLoading = false
                      done()
                    })
                }
            },
            searchChange(params,done) {
                params = this.filterForm(params)
                this.paramsSearch = params
                this.page.currentPage = 1
                this.getPage(this.page, params)
                done()
            },
            sortChange(val) {
                let prop = val.prop ? val.prop.replace(/([A-Z])/g, "_$1").toLowerCase() : '';
                if (val.order == 'ascending') {
                    this.page.descs = []
                    this.page.ascs = prop
                } else if (val.order == 'descending') {
                    this.page.ascs = []
                    this.page.descs = prop
                } else {
                    this.page.ascs = []
                    this.page.descs = []
                }
                this.getPage(this.page)
            },
            getPage(page, params) {
                this.tableLoading = true
                // if (this.paramsSearch.categoryId) {
                //     this.paramsSearch.categoryFirst = this.paramsSearch.categoryId[0]
                //     this.paramsSearch.categorySecond = this.paramsSearch.categoryId[1]
                // }
                getPage(Object.assign({
                    current: page.currentPage,
                    size: page.pageSize,
                    descs: this.page.descs,
                    ascs: this.page.ascs,
                }, params, this.paramsSearch)).then(response => {
                    let tableData = response.rows
                    // tableData.forEach(function (item, index) {
                    //     let categoryId = []
                    //     if(item.categoryFirst){
                    //       categoryId.push(item.categoryFirst)
                    //     }
                    //     if(item.categorySecond){
                    //       categoryId.push(item.categorySecond)
                    //     }
                    //     item.categoryId = categoryId
                    // })
                    this.tableData = tableData
                    this.page.total = response.total
                    this.page.currentPage = page.currentPage
                    this.page.pageSize = page.pageSize
                    this.tableLoading = false
                }).catch(() => {
                    this.tableLoading = false
                })
            },
            /**
             * @title 数据删除
             * @param row 为当前的数据
             * @param index 为当前删除数据的行数
             *
             **/
            handleDel: function (row, index) {
                var _this = this
                this.$confirm('是否确认删除此数据', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(function () {
                    return delObj(row.id)
                }).then(data => {
                    _this.$message({
                        showClose: true,
                        message: '删除成功',
                        type: 'success'
                    })
                    this.getPage(this.page)
                }).catch(function (err) {
                })
            },
            /**
             * @title 数据更新
             * @param form 为当前的数据
             * @param index 为当前更新数据的行数
             * @param done 为表单关闭函数
             *
             **/
            handleUpdate: function (form, index, done, loading) {
                if(typeof(form.map.latitude)!='undefined'){
                  form.latitude=form.map.latitude
                }else if(typeof(form.map.location.lat)!='undefined'){
                   form.latitude=form.map.location.lat
                }
                if(typeof(form.map.longitude)!='undefined'){
                  form.lontitude=form.map.longitude
                }else if(typeof(form.map.location.lng)!='undefined'){
                   form.lontitude=form.map.location.lng
                }
                form.address=form.map.formattedAddress
                if(form.files.length!=0){
                  form.files.forEach((item,index,arr)=>{
                    arr[index]['path']=arr[index]['value']
                    arr[index]['fName']=arr[index]['label']
                    arr[index]['type']=0
                  })
                }
                putObj(form).then(data => {
                    this.$message({
                        showClose: true,
                        message: '修改成功',
                        type: 'success'
                    })
                    done()
                    this.getPage(this.page)
                }).catch(() => {
                    loading()
                })
            },
            /**
             * @title 数据添加
             * @param row 为当前的数据
             * @param done 为表单关闭函数
             *
             **/
            handleSave: function (form, done, loading) {       
                if(form.files.length!=0){
                  form.files.forEach((item,index,arr)=>{
                    arr[index]['path']=arr[index]['value']
                    arr[index]['fName']=arr[index]['label']
                    arr[index]['type']=0
                  })
                }
                if(typeof(form.map.latitude)!='undefined'){
                  form.latitude=form.map.latitude
                }else if(typeof(form.map.location.lat)!='undefined'){
                   form.latitude=form.map.location.lat
                }
                if(typeof(form.map.longitude)!='undefined'){
                  form.lontitude=form.map.longitude
                }else if(typeof(form.map.location.lng)!='undefined'){
                   form.lontitude=form.map.location.lng
                }
                // form.lontitude=form.map.lontitude
                // form.latitude=form.map.longitude
                form.address=form.map.formattedAddress
                delete form.id
                addObj(form).then(data => {
                    this.$message({
                        showClose: true,
                        message: '添加成功',
                        type: 'success'
                    })
                    // console.log(form)
                    done()
                    this.getPage(this.page)
                }).catch(() => {
                    loading()
                })
            },
            /**
             * 刷新回调
             */
            refreshChange(page) {
              this.getPage(this.page)
            },

            uploadBefore: function(file, done, loading, column) {
              // let newFile = new File([file], {name: file.name});
              // console.log(newFile, '1111.'+file.type)
                done();
              //  column.data = {fileName: file.name};  //设置上传参数
              //  column.headers = {  'Authorization': 'Bearer ' + getToken()};  //设置上传参数
              // //  console.log(Object.assign(column.headers, { "Content-Type": "multipart/form-data" }))
              //  console.log("file:",file)
              //  console.log("column:",column)
              //  done();
            },
        }
    }
</script>
